using Services;
using Skills;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SkillUI_SelectPanel : UI_Dynamic
{
    [SerializeField]
    private Transform transform_content;
    private Scrollbar bar;

    private Player player;

    private readonly Comparer_SkillPanel comparer = new Comparer_SkillPanel();

    private const int NUM_BUTTON = 20;
    private readonly List<GameObject> buttons = new List<GameObject>();
    private int curNum;

    private void Start()
    {
        bar = GetComponentInChildren<Scrollbar>();
        immediate_next = true;
        Visible = false;
        player = ServiceLocator.Get<ActionController>().player;
        EventSystem eventSystem = ServiceLocator.Get<EventSystem>();
        eventSystem.AddListener<EGameState, EGameState>(EEvent.GameStateChange, OnGameStateChange);
        GenerateButtons();
    }

    private void GenerateButtons()
    {
        GameObject prototype = GetComponentInChildren<SkillUI_Button>().gameObject;
        prototype.SetActive(false);
        for (int i = 0; i < NUM_BUTTON; ++i)
        {
            buttons.Add(Instantiate(prototype, transform_content.transform));
        }
        Destroy(prototype);
        curNum = 0;
    }

    private void Show()
    {
        InstallSkill();
        Move(Input.mousePosition);
        bar.value = 1;
        Visible = true;
    }

    private void InstallSkill()
    {
        List<RuntimeSkill> skills = player.SkillManager.GetAvailablelSkills(player.sect);
        skills.Sort(comparer);
        GameObject obj;
        int i = 0;
        for (; i < skills.Count; ++i)
        {
            obj = buttons[i];
            if (i >= curNum)
                obj.SetActive(true);
            obj.GetComponent<SkillUI_Button>().Initialize(skills[i]);
        }
        for (; i < curNum; ++i)
        {
            buttons[i].SetActive(false);
        }
        curNum = skills.Count;
    }

    private void OnGameStateChange(EGameState from, EGameState to)
    {
        switch (to)
        {
            case EGameState.OpenSkillPanel:
                Visible = true;
                Show();
                break;
            default:
                Visible = false;
                break;
        }
    }
}
